const querystring = require('querystring');
const { getPostData,formatGetToPostParams } = require('./util');
const handelBlogRouter = require('./router/blog');
const handelUserRouter = require('./router/user');
const SESSION_DATA  = {}
const serverHandel = (req, res) => {
  // SESSION_DATA.req = req;
  req.path = req.url.split('?')[0];
  req.query = querystring.parse(req.url.split('?')[1]);
  req.cookie = formatGetToPostParams(req.headers.cookie)

  let uuid = req.cookie.uuid;
  if(uuid){
    if(!SESSION_DATA[uuid]){
      SESSION_DATA[uuid] ={}
    }
  }else{
    uuid = `${Date.now()}_${Math.random()}`
    const currentTime = (new Date()).getTime()
    SESSION_DATA[uuid]={}
    res.setHeader('Set-Cookie',`uuid=${uuid};expires=${new Date(currentTime+24*60*60*1000)};path=/;`)
  }
  req.session = SESSION_DATA[uuid]
  
  res.setHeader('Content-type', 'application/json');
  getPostData(req, res).then((postData) => {
    req.body = postData;

    // 处理博客路由
    const blogResult = handelBlogRouter(req, res);
    if (blogResult) {
      blogResult.then((blogData) => {
        res.end(JSON.stringify(blogData));
      });
      return;
    }

    // 处理用户路由
    const userResult = handelUserRouter(req, res);
    if (userResult) {
      userResult.then((userData) => {
        res.end(JSON.stringify(userData));
      });
      return;
    }
    res.writeHead(404, { 'Content-Type': 'text/plain' }).end('404 Not Found');
  });
};
module.exports = serverHandel;
